package me.wanghongyu.railwayquery.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import com.google.gson.Gson;
import com.rnkrsoft.bopomofo4j.Bopomofo4j;
import lombok.SneakyThrows;
import me.wanghongyu.railwayquery.Main;
import me.wanghongyu.railwayquery.model.Ticket;
import me.wanghongyu.railwayquery.model.TrainInfo;
import me.wanghongyu.railwayquery.model.pojo.JsonRootBean;
import me.wanghongyu.railwayquery.model.pojo.Message;
import me.wanghongyu.railwayquery.model.pojo.Seats;
import me.wanghongyu.railwayquery.model.pojo.Trains;
import okhttp3.*;
import me.wanghongyu.railwayquery.view.QueryView;


public class QueryUtils {

	public static final String APIURL = "https://i.meituan.com/uts/train/train/querytripnew?fromPC=1&train_source=meituanpc@wap&uuid=a2bab8b38b364d7f8d7a.1590661315.1.0.0&from_station_telecode=%s&to_station_telecode=%s&yupiaoThreshold=0&start_date=%s&isStudentBuying=false";

	private static OkHttpClient client = new OkHttpClient();

	private static Map<String,String> locationMap;

	private static Map<String,String[]> locationPinYinMap;

	private static String cookie = "iuuid=A816A0CDDB2F37019960913AE6799D225EF72A482FA9B054E; ci=1; cityname=1; webp=1; _lxsdk_cuid=17959183bfac8-06c14fcd2ddc41-d7e1739-1fa400-17959183bfac8; _lxsdk=A1816A0CDDB2F37019960913AE6799D225EF72A48757BA3CBB1CBA4EEFA9B054E; i_extend=H__1a100001__b1; __mta=20938375.1620697431332.1620697431332.1620697431332.1; __utma=745970106.15331219383.16206974311.1620697431.1620697431.1; __utmz=74197006.1620697431.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); latlng=301.144839,1201.752955,1620697431771";


	/*
	获取当天铁路信息并转换为实体类
	 */
	
	public static List<TrainInfo> getTrainInfo(String start,String end,String date,boolean isStudent) throws IOException {
		List<TrainInfo> trainInfoList = new ArrayList<>();

		//format.format(new Date())
		String newUrl = String.format(APIURL, getLocationId(start), getLocationId(end),date);
		System.out.println(newUrl);
		Request request = new Request.Builder()
				.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)")
				.addHeader("Cookie",cookie)
				.url(newUrl)
				.get()
				.build();
		Response response = client.newCall(request).execute();

		/*
		获取返回json并处理
		 */

		String jsonStr = response.body().string();
		System.out.println(jsonStr);
		JsonRootBean jsonRoot;
		List<Trains> trains;
		try{
			jsonRoot = new Gson().fromJson(jsonStr, JsonRootBean.class);
			trains = jsonRoot.getData().getTrains();
		}catch (Exception err){
			QueryView.message(new Gson().fromJson(jsonStr, Message.class).getMessage());
			return null;
		}


		for (Trains train : trains) {
			TrainInfo ti = new TrainInfo(train.getFull_train_code(),train.getFrom_station_name(),train.getTo_station_name(),train.getStart_time(),train.getArrive_time(),train.getRun_time_minute());
			List<Seats> seats = train.getSeats();
			for (Seats seat : seats) {
				Ticket ticket;
				if(isStudent){
					ticket = new Ticket(seat.getSeat_type_name(),seat.getStudentPrice(),seat.getSeat_yupiao());
				}else{
					ticket = new Ticket(seat.getSeat_type_name(),seat.getSeat_price(),seat.getSeat_yupiao());
				}
				ti.addTicket(ticket);
			}
			trainInfoList.add(ti);
		}
		return trainInfoList;
	}

	/*
	读取地点名 : 地点ID 表
	 */
	@SneakyThrows
	public static Map<String,String> getDataCache(){
		if(locationMap == null) {
			locationMap = new HashMap<>();
			InputStream fis = Main.class.getResourceAsStream("/station_name.txt");
			byte[] bs = new byte[1024];
			String str = "";
			int size = fis.read(bs);
			while(size != -1) {
				str += new String(bs,0,size,"UTF-8");
				size = fis.read(bs);
			}
			String[] strs = str.split("\n");
			for (String s : strs) {
				locationMap.put(s.split(" ")[0],s.split(" ")[1]);
			}
		}
		return locationMap;
	}

	@SneakyThrows
	public static Map<String,String[]> getPinYinMap(){
		if(locationPinYinMap == null){
			locationPinYinMap = new HashMap<>();
			Bopomofo4j.local();
			Set<String> keySet = getDataCache().keySet();
			//拼音API处理一些词时会报错
			keySet.remove("三十里堡");
			locationPinYinMap.put("三十里堡",new String[]{"San","Shi","Li","Bao"});
			keySet.remove("柴沟堡");
			locationPinYinMap.put("柴沟堡",new String[]{"Chai","Gou","Bao"});
			for (String s : keySet) {
				locationPinYinMap.put(s, Bopomofo4j.pinyin(s,2,false,true," ").split(" "));
			}
		}
		return locationPinYinMap;
	}

	/*
		获取地点名对应的地点ID
	 */

	public static String getLocationId(String location){
		String id = getDataCache().get(location);
		if(id == null) return "";
		return id;
	}

	/*
	根据输入内容搜索地名
	搜索机制
	- 地名前几个字
	- 地名拼音首字母
	- 地名拼音
	*/

	public static Set<String> getLocationList(String name){
		name = name.toUpperCase();

		Set<String> set = new HashSet<>();
		//地名前几个字
		Set<String> locationList = QueryUtils.getDataCache().keySet();
		for (String s : locationList) {
			if(s.startsWith(name)){
				set.add(s);
			}
		}
		//地名拼音首字母 + 地名拼音
		locationList = QueryUtils.getPinYinMap().keySet();
		for (String s : locationList) {
			String[] words = QueryUtils.getPinYinMap().get(s);
			if(StringUtils.mergeStringArray(words).toUpperCase().startsWith(name)){
				set.add(s);
				continue;
			}
			if(StringUtils.getStringArrayInitials(words).toUpperCase().startsWith(name)){
				set.add(s);
			}
		}
		return set;
	}
	
}


